{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Migrating from Spark to BigQuery via Dataproc -- Part 4\n",
    "\n",
    "* [Part 1](01_spark.ipynb): The original Spark code, now running on Dataproc (lift-and-shift).\n",
    "* [Part 2](02_gcs.ipynb): Replace HDFS by Google Cloud Storage. This enables job-specific-clusters. (cloud-native)\n",
    "* [Part 3](03_automate.ipynb): Automate everything, so that we can run in a job-specific cluster. (cloud-optimized)\n",
    "* [Part 4](04_bigquery.ipynb): Load CSV into BigQuery, use BigQuery. (modernize)\n",
    "* [Part 5](05_functions.ipynb): Using Cloud Functions, launch analysis every time there is a new file in the bucket. (serverless)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Catch-up cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Catch-up cell. Run if you did not do previous notebooks of this sequence\n",
    "!wget http://kdd.ics.uci.edu/databases/kddcup99/kddcup.data_10_percent.gz\n",
    "BUCKET='cloud-training-demos-ml'  # CHANGE\n",
    "!gcloud storage cp kdd* gs://$BUCKET/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load data into BigQuery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!bq mk sparktobq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BUCKET='cloud-training-demos-ml'  # CHANGE\n",
    "!bq --location=US load --autodetect --source_format=CSV sparktobq.kdd_cup_raw gs://$BUCKET/kddcup.data_10_percent.gz"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### BigQuery queries\n",
    "\n",
    "We can replace much of the initial exploratory code by SQL statements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM sparktobq.kdd_cup_raw LIMIT 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ooops. There are no column headers. Let's fix this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "\n",
    "CREATE OR REPLACE TABLE sparktobq.kdd_cup AS\n",
    "\n",
    "SELECT \n",
    "    int64_field_0 AS duration,\n",
    "    string_field_1 AS protocol_type,\n",
    "    string_field_2 AS service,\n",
    "    string_field_3 AS flag,\n",
    "    int64_field_4 AS src_bytes,\n",
    "    int64_field_5 AS dst_bytes,\n",
    "    int64_field_6 AS wrong_fragment,\n",
    "    int64_field_7 AS urgent,\n",
    "    int64_field_8 AS hot,\n",
    "    int64_field_9 AS num_failed_logins,\n",
    "    int64_field_11 AS num_compromised,\n",
    "    int64_field_13 AS su_attempted,\n",
    "    int64_field_14 AS num_root,\n",
    "    int64_field_15 AS num_file_creations,\n",
    "    string_field_41 AS label\n",
    "FROM\n",
    "    sparktobq.kdd_cup_raw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM sparktobq.kdd_cup LIMIT 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Spark analysis\n",
    "\n",
    "Replace Spark analysis by BigQuery SQL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery connections_by_protocol\n",
    "SELECT COUNT(*) AS count\n",
    "FROM sparktobq.kdd_cup\n",
    "GROUP BY protocol_type\n",
    "ORDER by count ASC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "connections_by_protocol"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Spark SQL to BigQuery\n",
    "\n",
    "Pretty clean translation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery attack_stats\n",
    "                           SELECT \n",
    "                             protocol_type, \n",
    "                             CASE label\n",
    "                               WHEN 'normal.' THEN 'no attack'\n",
    "                               ELSE 'attack'\n",
    "                             END AS state,\n",
    "                             COUNT(*) as total_freq,\n",
    "                             ROUND(AVG(src_bytes), 2) as mean_src_bytes,\n",
    "                             ROUND(AVG(dst_bytes), 2) as mean_dst_bytes,\n",
    "                             ROUND(AVG(duration), 2) as mean_duration,\n",
    "                             SUM(num_failed_logins) as total_failed_logins,\n",
    "                             SUM(num_compromised) as total_compromised,\n",
    "                             SUM(num_file_creations) as total_file_creations,\n",
    "                             SUM(su_attempted) as total_root_attempts,\n",
    "                             SUM(num_root) as total_root_acceses\n",
    "                           FROM sparktobq.kdd_cup\n",
    "                           GROUP BY protocol_type, state\n",
    "                           ORDER BY 3 DESC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "ax = attack_stats.plot.bar(x='protocol_type', subplots=True, figsize=(10,25))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Write out report\n",
    "\n",
    "Copy the output to GCS so that we can safely delete the AI Platform Notebooks instance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import google.cloud.storage as gcs\n",
    "\n",
    "# save locally\n",
    "ax[0].get_figure().savefig('report.png');\n",
    "connections_by_protocol.to_csv(\"connections_by_protocol.csv\")\n",
    "\n",
    "# upload to GCS\n",
    "bucket = gcs.Client().get_bucket(BUCKET)\n",
    "for blob in bucket.list_blobs(prefix='sparktobq/'):\n",
    "    blob.delete()\n",
    "for fname in ['report.png', 'connections_by_protocol.csv']:\n",
    "    bucket.blob('sparktobq/{}'.format(fname)).upload_from_filename(fname)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
